'use strict';

const Controller = require('egg').Controller;
const fs = require('fs')
const path = require('path')
//异步二进制，写入流
const awaitWriteStrem = require('await-stream-ready').write
//管道读入一个虫洞
const sendToWormhole = require('stream-wormhole')
const dayjs = require('dayjs')
class FileController extends Controller {
  async upload() {
    const stream = await this.ctx.getFileStream()
    //基础目录
    const uploadBasePath = 'app/public/uploads';
    //生成文件名
    console.log(stream.filename);
    const filename = `${Date.now()}${Number.parseInt(
      Math.random() * 1000
    )}${path.extname(stream.filename).toLocaleLowerCase()}`;
    const dirname = dayjs(Date.now()).format('YYYY/MM/DD');
    function mkdirsSync(dirname) {
      if (fs.existsSync(dirname)) {
        return true
      } else {
        if (mkdirsSync(path.dirname(dirname))) {
          fs.mkdirSync(dirname);
          return true
        }
      }
    }
    mkdirsSync(path.join(uploadBasePath, dirname));
    //生成写入路径
    const target = path.join(uploadBasePath, dirname, filename);
    console.log(target);
    //写入流
    const writeStream = fs.createWriteStream(target)
    try {
      //异步把文件流写入
      await awaitWriteStrem(stream.pipe(writeStream))
    } catch (err) {
      //如果出现错误，关闭管道
      await sendToWormhole(stream)
      this.ctx.throw(500, err)
    }
    const { protocol, host } = this.ctx.request
    let url = path.join('/public/uploads', dirname, filename).replace(/\\|\//g, '/')
    url = protocol + '://' + host + url
    console.log(url);
    this.ctx.apiSuccess({ url })

  }
  async uploadAvatar() {
    const { ctx } = this;
    let { avatar } = ctx.request.body
    const { protocol, host } = this.ctx.request
    var path = 'app/public/uploads/avatar/' + Date.now() + '.png';//路径从app.js级开始找--
    var base64 = avatar.replace(/^data:image\/\w+;base64,/, ""); //去掉图片base64码前面部分data:image/png;base64
    //把base64码转成buffer对象，
    var dataBuffer = Buffer.from(base64, 'base64');
    ctx.apiSuccess(protocol + '://' + host+path.slice(3))
    await fs.writeFile(path, dataBuffer, err => {

    })

  }
}

module.exports = FileController;
